package com.example.lvsuo.proxy;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import com.example.lvsuo.annotation.File;
import com.example.lvsuo.modal.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Component
@Aspect
public class FileProxy {
    @Around("@annotation(f)")
    public Result around(ProceedingJoinPoint jp, File f) throws Throwable{
        Object[] args = jp.getArgs();
        MultipartFile img= (MultipartFile) args[0];
        String endpoint = "";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "";
        String accessKeySecret = "";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);



        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest("wu-demo",img.getOriginalFilename(),img.getInputStream());

        // 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);
        String bucketName = "wu-demo";
        String objectName = img.getOriginalFilename();
        // 上传文件。
        ossClient.putObject(putObjectRequest);
        Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 10);

        String url = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString();
        // 关闭OSSClient。
        ossClient.shutdown();

        return Result.back(url);
    }
}
